﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using GroundWater.BusinessActions;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;

namespace GroundWater.waterlevel
{
    public partial class WaterLevelByDate : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "水位曲线图");
            if (!this.IsPostBack)
            {
                txtStartDate.Value = DateTime.Now.AddDays(-10).ToString("yyyy-MM-dd");
                txtEndDate.Value = DateTime.Now.ToString("yyyy-MM-dd");

                //drpWell.DataBind();

                //GenerateImage();
            }
            else
            {
                if (drpWell.SelectedIndex == 0)
                {
                    GenerateImage();
                }
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            object o = drpWell.SelectedItem;
        }

        protected void drpWell_SelectedIndexChanged(object sender, EventArgs e)
        {
            GenerateImage();
        }

        
        protected void drpChartType_SelectedIndexChanged(object sender, EventArgs e)
        {

            GenerateImage();
        }

        protected void drp3D_SelectedIndexChanged(object sender, EventArgs e)
        {
            GenerateImage();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            //string wellCode = drpWell.SelectedValue;
            //string startDate = txtStartDate.Value;
            //string endDate = txtEndDate.Value;

            //updPanel.Update();
            if (WaterLevelChart.Series["Series1"].Points.Count == 0)
            {
                GenerateImage();
            }
        }

        private void GenerateImage()
        {
            int maxDay = 0;
            if(Husb.Util.CommonUtil.IsInteger(txtMarker.Value))
            {
                maxDay = Int32.Parse(txtMarker.Value);
            }

            DataTable dt = Monitoring.FetchWaterLeveGroupByDate(drpWell.SelectedItem.Value, txtStartDate.Value, DateTime.Parse(txtEndDate.Value).ToString("yyyy-MM-dd"), maxDay);
            //
            if (dt == null || dt.Rows.Count == 0) return;
            var waterLevels = dt.AsEnumerable().Where( r => (decimal)r["Waterlevel"] >= 0);
            if (waterLevels.Count() == 0)
            {
                RegisterClientScript("alert('本时间段的水位为负数，系统数据不合理。');", lblJavaScript);
                return;
            }

            var min = (from waterlevel in waterLevels select (decimal)waterlevel["Waterlevel"]).Min();
            var max = (from waterlevel in waterLevels select (decimal)waterlevel["Waterlevel"]).Max();
            var interval = (max - min) / 10;
            var sub = max - min;

            if (sub < 0.03m)
            {
                sub = 0.03m;
            }

            min = min - sub / 2;
            if (min < 0) min = 0;
            max = max + sub / 2;
            if (max < 0)
            {
                RegisterClientScript("alert('本时间段的最大水位为负数，系统数据不合理。');", lblJavaScript);
                return;
            }

            if (max == 0)
            {
                RegisterClientScript("alert('本时间段的最大水位为0，系统数据不合理。');", lblJavaScript);
                return;
            }

            if (max < min )
            {
                RegisterClientScript("alert('本时间段的最大水位为" + max.ToString() + "，最小水位为" + min.ToString() + "，系统数据不合理。');", lblJavaScript);
                return;
            }

            if (max == min)
            {
                max = max + max / 2;
                min = min - min / 2;
            }

            Chart chart = WaterLevelChart;// WaterLevelChart;
            int width = 726;
            int height = 342;
            if (Husb.Util.CommonUtil.IsInteger(txtWidth.Value))
            {
                width = Int32.Parse(txtWidth.Value);
            }
            if (Husb.Util.CommonUtil.IsInteger(txtHeight.Value))
            {
                height = Int32.Parse(txtHeight.Value);
            }
            chart.Width = new Unit(width);
            chart.Height = new Unit(height);

            SeriesChartType chartType = SeriesChartType.Line;// (SeriesChartType)Enum.Parse(typeof(SeriesChartType), drpChartType.SelectedItem.Value, true);

            Series series = chart.Series["Series1"];
            series.ChartType = chartType;
            series["DrawingStyle"] = "Emboss";//Emboss
            //if (drp3D.SelectedIndex == 1)
            //{
            //    chart.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            //    series["DrawingStyle"] = "Cylinder";
            //}
            series.IsValueShownAsLabel = true;

            chart.Titles["Title1"].Text = drpWell.SelectedItem.Text + " 水井的水位变化曲线图";
            ChartArea chartArea = chart.ChartAreas["ChartArea1"];
            chartArea.AxisY.Title = "水位 单位：米";
            chartArea.AxisY.TitleFont = new System.Drawing.Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);
            // Set X axis margin
            chartArea.AxisX.IsMarginVisible = true;
            chartArea.AxisY.IsStartedFromZero = false;
            chartArea.AxisY.Minimum = Math.Round( Convert.ToDouble(min), 2);
            chartArea.AxisY.Maximum = Math.Round(Convert.ToDouble(max), 2);
            chartArea.AxisY.Interval = Convert.ToDouble(Math.Round(interval, 2));

            series.Points.Clear();
            //series.LabelAngle = 60;
            
            DateTime first = DateTime.MinValue;
            int week = 0;
            if(dt.Rows.Count > 0)
            {
                string date = dt.Rows[0]["MonitorTime"].ToString();
                if (date.Length > 2)
                {
                    first = DateTime.Parse(date);
                }
                else
                {
                    week = Int32.Parse(date);
                }
            }

            foreach (DataRow row in dt.Rows)
            {
                DateTime monitorTime = DateTime.MinValue;
                if (week == 0)
                {
                    monitorTime = DateTime.Parse((string)row["MonitorTime"]);
                }
                else
                {
                    week = Int32.Parse((string)row["MonitorTime"]);
                }
                decimal waterlevel = (decimal)row["Waterlevel"];
                if (waterlevel < 0)
                {
                    continue;
                }

                double x = week > 0? week : monitorTime.Subtract(first).Days;
                double y = Convert.ToDouble(waterlevel);

                DataPoint p = new DataPoint(x, y);

                p.AxisLabel = week > 0 ? week.ToString() + "周" : monitorTime.ToString("MMdd");
                //p.LabelAngle = 60;
                
                p.Label = Math.Round(y, 2).ToString();

                series.Points.Add(p);

                //series.Points.AddY(y);
            }
        }

        protected void drpWell_DataBound(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            if (!String.IsNullOrEmpty(id))
            {
                foreach (ListItem item in drpWell.Items)
                {
                    if (item.Value == id)
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }

            if (!this.IsPostBack)
            {
                GenerateImage();
            }
            else
            {
                
            }
        }

        //protected void Button1_Click(object sender, EventArgs e)
        //{
        //    int i = Monitoring.WeekOfYear(DateTime.Parse(txtStartDate.Value));
        //    int j = WeekOfYear(DateTime.Parse(txtStartDate.Value));
        //    int k = WeekOfYear1(DateTime.Parse(txtStartDate.Value));
        //    int p = 1;

        //}

        //private int GetWeeksOfDayInMonth(DateTime dt)
        //{
        //    DateTime monthFirstDay = DateTime.Parse(dt.Year.ToString() + "-" + dt.Month.ToString() + "-1");
        //    int startDay = 1;//第一周从哪天开始 
        //    int dayOfOneWeek = 0;//第一周有几天 
        //    switch (monthFirstDay.DayOfWeek)
        //    {
        //        case DayOfWeek.Monday: dayOfOneWeek = 7; startDay = 1;
        //            break;
        //        case DayOfWeek.Tuesday: dayOfOneWeek = 6; startDay = 1;
        //            break;
        //        case DayOfWeek.Wednesday: dayOfOneWeek = 5; startDay = 1;
        //            break;
        //        case DayOfWeek.Thursday: dayOfOneWeek = 4; startDay = 1;
        //            break;
        //        case DayOfWeek.Friday: dayOfOneWeek = 7; startDay = 4;
        //            break;
        //        case DayOfWeek.Saturday: dayOfOneWeek = 7; startDay = 3;
        //            break;
        //        case DayOfWeek.Sunday: dayOfOneWeek = 7; startDay = 2;
        //            break;
        //    }
        //    int returnValue = 0;
        //    int span = dt.Day - startDay;
        //    if (span < 0)
        //        returnValue = 0;
        //    else
        //        returnValue = span < dayOfOneWeek ? 1 : ((span - dayOfOneWeek) / 7 + 2);
        //    return returnValue;
        //}

        //public static int WeekOfYear(DateTime curDay)
        //{
        //    int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "- " + "1-1 ").DayOfWeek);

        //    int days = curDay.DayOfYear;
        //    int daysOutOneWeek = days - (7 - firstdayofweek);

        //    if (daysOutOneWeek <= 0)
        //    {
        //        return 1;
        //    }
        //    else
        //    {
        //        int weeks = daysOutOneWeek / 7;
        //        if (daysOutOneWeek % 7 != 0)
        //            weeks++;

        //        return weeks + 1;
        //    }
        //}

        //public static int WeekOfYear1(DateTime curDay)
        //{
        //    System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
        //    int weekOfYear = gc.GetWeekOfYear(curDay, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
        //    return weekOfYear;
        //}

    }
}
